package service

import (
	"encoding/json"
	"fmt"
	"io"
	"net/http"
	"net/url"
	"strings"
	"time"

	"zhonghui/console/warehouse/helperx"
)

type SmsResponse struct {
	ReqMsg  string `json:"ReqMsg"`
	ReqId   string `json:"ReqId"`
	ReqCode string `json:"ReqCode"`
}

func replacePlaceholders(content string, param []string) string {
	placeholder := "${TXT_20}"
	for _, p := range param {
		if strings.Contains(content, placeholder) {
			content = strings.Replace(content, placeholder, p, 1)
		}
	}
	return content
}

func SendZhongHuiJDSms(phone string, param []string, content string) (bool, string) {
	endpoint := "https://sms-yx.jdcloud.com/HttpSmsMt"
	pwd := "7f7d7b7bca734b474c299c1dbde065bb"

	mt := time.Now().Format("20060102150405")

	finalContent := replacePlaceholders(content, param)
	fmt.Println(finalContent)

	form := url.Values{}
	form.Add("name", "zhccyx")
	form.Add("pwd", helperx.EasyMD5(pwd+mt))
	form.Add("phone", phone)
	form.Add("content", finalContent)
	form.Add("mttime", mt)
	form.Add("rpttype", "1")

	req, err := http.NewRequest("POST", endpoint, strings.NewReader(form.Encode()))
	if err != nil {
		return false, fmt.Sprintf("创建请求失败: %v", err)
	}
	req.Header.Set("Content-Type", "application/x-www-form-urlencoded; charset=utf-8")

	client := &http.Client{}
	resp, err := client.Do(req)
	if err != nil {
		return false, fmt.Sprintf("请求发送失败: %v", err)
	}
	defer resp.Body.Close()

	body, err := io.ReadAll(resp.Body)
	if err != nil {
		return false, fmt.Sprintf("读取响应失败: %v", err)
	}

	fmt.Println(string(body))

	var smsResp SmsResponse
	if err := json.Unmarshal(body, &smsResp); err != nil {
		return false, fmt.Sprintf("JSON解析失败: %v，原始响应: %s", err, string(body))
	}

	if smsResp.ReqCode == "00" {
		return true, smsResp.ReqId
	}
	return false, fmt.Sprintf("发送失败，代码: %s，信息: %s", smsResp.ReqCode, smsResp.ReqMsg)
}
